package orchestration.persistence;

import java.io.FileNotFoundException;
import java.io.InputStream;

import orchestration.businessprocess.model.BusinessProcessModel;
import orchestration.persistence.OrchestratorAuthority.AndroidProcess;
import orchestration.persistence.exceptions.OrchestrationDAOException;
import orchestration.persistence.sqlite.OrchestratorDatabaseHelper;
import orchestration.xml.BpmParsingException;
import orchestration.xml.BpmXmlFactory;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

public class BusinessProcessModelDAOImpl implements BusinessProcessModelDAO{

	@Override
	public BusinessProcessModel getBusinessProcessModel(Uri uri,Context mContext) throws OrchestrationDAOException {
		if(sUriMatcher.match(uri)!=PROCESS_ID)
			throw new OrchestrationDAOException("Invalid URI to load a process: " + uri);
		Cursor c= mContext.getContentResolver().query(uri, OrchestratorDatabaseHelper.PROCESS_FIELDS, null, null, null);
		c.moveToFirst();
		if(c.isAfterLast())
			throw new OrchestrationDAOException("No BPM found for URI: " + uri);
		String path= c.getString(c.getColumnIndex(AndroidProcess.PATH));
		c.close();
		Uri pathUri= Uri.parse(path);
		try {
			InputStream in= mContext.getContentResolver().openInputStream(pathUri);
			return BpmXmlFactory.getBPM(in);
		} catch (FileNotFoundException e) {
			throw new OrchestrationDAOException("The bpmn file could not be found: " + path);
		} catch (BpmParsingException e) {
			throw new OrchestrationDAOException("Error while parsing the bpmn file " + e.getMessage());
		}
	}

	private static final UriMatcher sUriMatcher;
	private static final int PROCESS_ID=1;

	static{
		sUriMatcher= new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(OrchestratorAuthority.AUTHORITY, "processes/#", PROCESS_ID);
	}
}
